package com.glory.brepda.activity.mfg;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.SampleListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotList;
import com.glory.brepda.entity.SimpleEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.glory.brepda.utils.ShowDialog;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * FileName: FTTrackOutBiandaiActivity
 * Author: XJH
 * Date: 2020/5/22 9:08
 * Description:编带出站FT测试
 * 点击提交按钮，请求接口，根据接口返回信息跳转正常出站、异常出站界面，正常出站成功后，跳转清料页面
 * History:
 */
public class FTTrackOutBiandaiActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpMainWork)
    FreeUI_ClearEditText etEqpMainWork;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.tvHoldState)
    TextView tvHoldState;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvSampleList)
    RecyclerView rvSampleList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llLotList)
    LinearLayout llLotList;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.tvCode)
    TextView tvCode;
    @BindView(R.id.flList)
    FrameLayout flList;
    private SampleListAdapter mSampleListAdapter;
    private FreeUI_GeneralPop codePop;
    private ArrayList<String> lotList = new ArrayList<>();
    private String mEqpID = "";
    private String mPackageType = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_out_biandai_ft;
    }

    @Override
    protected void initView() {
        initLayout();
    }

    private void initLayout() {
        llLotList.setVisibility(View.VISIBLE);
        listTv1.setText("BIN名称");
        listTv2.setText("BIN描述");
        listTv3.setText("数量");
        listTv4.setText("占比良率");
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        tvBaseSubmit.setText("下一步");
        initRecyclerView(rvSampleList,this);
        mSampleListAdapter = new SampleListAdapter(null,false);
        mSampleListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mSampleListAdapter.isFirstOnly(true);
        rvSampleList.setAdapter(mSampleListAdapter);
        addActivity(this);




//        initEdit(etEqpMainWork,s ->{
//            FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
//                    ("正在查询LOT信息", new TypeToken<BaseResponseBean<LotInfoEntity>>() {
//                    }.getType(), getSupportFragmentManager(), this) {
//
//                @Override
//                public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
//                    super.onSuccess(response);
//                    if (response.body().isSuccess(FTTrackOutBiandaiActivity.this, true, getSupportFragmentManager())) {
//                        if (response.body().getResponse().getBody().getLOTLIST().size() > 0){
//                            etLot.setText(response.body().getResponse().getBody().getLOTLIST().get(0).getLOTID());
//                            getLotData(response.body().getResponse().getBody().getLOTLIST().get(0).getLOTID());
//                        }else {
//                            showToast("未查询到批号信息",false);
//                        }
//                    }
//                }
//                @Override
//                public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
//                    super.onError(response);
//
//                }
//            };
//
//            JsonObject map = new JsonObject();
//            map.addProperty("ACTIONTYPE", "LOTLISTRUNBYEQP");
//            map.addProperty("LOTID", "");
//            map.addProperty("LOTALIAS", "");
//            map.addProperty("DURABLE", "");
//            map.addProperty("EQUIPMENTID", s);
//            map.addProperty("STEPNAME", "");
//            NetUtils.requestPostNet("IF.LOTQUERY", "Common", FTTrackOutBiandaiActivity.this, map, callBack);
////
////            requestData(getText(etLot),s);
//        });

    }

    private void getLotData(String lotID) {
        LotUtils.searchLotInfo(FTTrackOutBiandaiActivity.this, lotID, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {

                if(StringUtils.isNotEmpty(response.getTip())){
                    ShowDialog.showDialog(FTTrackOutBiandaiActivity.this,response.getTip(),"制程风险提示");
                }
                mEqpID = response.getLOT().getEQUIPMENTID();
                tvLotNum.setText(response.getLOT().getMAINQTY());
                tvHoldState.setText(response.getLOT().getHOLDSTATE());
                mPackageType = response.getLOT().getMAINMATTYPE();
                etEqpMainWork.setText(response.getLOT().getEQUIPMENTID());
                mSampleListAdapter.setMainQTY(Integer.parseInt(response.getLOT().getMAINQTY()));
                requestBinInfo(lotID,"SelectBinData");
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"LOTQUERY");
            }
        });
    }

    private void requestBinInfo(String lotID,String actionType) {
        FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    SimpleEntity entity = response.body().getResponse().getBody();
                    if (!entity.getTRACKSHOWMSG().equals("")){
                        FreeApi_DialogUtils.getConfirmDialog(FTTrackOutBiandaiActivity.this, "确定", entity.getTRACKSHOWMSG(), () -> {
                            if (actionType.equals("SelectBinData")){
                                if (entity.getLOTBINDATALIST().size() <= 0){
                                    showToast("暂无BIN测试数据",false);
                                    return;
                                }

                                List<SimpleEntity.MantissaLotBinData> list = new ArrayList<>();
                                Map<String,SimpleEntity.MantissaLotBinData> map = new HashMap<>();
                                for (int i = 0; i < entity.getLOTBINDATALIST().size(); i++) {
                                    if (map.containsKey(entity.getLOTBINDATALIST().get(i).getBINNAME())){
                                        SimpleEntity.MantissaLotBinData mantissaLotBinData1 = entity.getLOTBINDATALIST().get(i);
                                        SimpleEntity.MantissaLotBinData mantissaLotBinData = map.get(entity.getLOTBINDATALIST().get(i).getBINNAME());
                                        mantissaLotBinData.setMAINQTY(mantissaLotBinData.getMAINQTY() + mantissaLotBinData1.getMAINQTY());
                                        map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),mantissaLotBinData);
                                    }else {
                                        map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),entity.getLOTBINDATALIST().get(i));
                                    }
                                }

                                for(Map.Entry<String, SimpleEntity.MantissaLotBinData> entry : map.entrySet()){
                                    list.add(entry.getValue());
                                }
                                mSampleListAdapter.setNewData(list);
                            }else {
                                Bundle bundle = new Bundle();
                                bundle.putString("LOTID",getText(etLot));
                                bundle.putString("EQPID",mEqpID);
                                bundle.putString("LOTNUM",tvLotNum.getText().toString());
                                bundle.putString("PACKAGETYPE",mPackageType);
                                FreeApi_Utils.skipWithExtraIntent("", bundle,FTTrackOutBiandaiActivity.this, entity.getGUIDE().equals("FAIL")?
                                        FTTrackOutBiandaiErrorActivity.class : FTTrackOutBiandaiSuccessActivity.class);
//                        finish();
                            }
                            return;
                        }).show(getSupportFragmentManager(),"CONFIRM_DIALOG");
                    }
                    if (actionType.equals("SelectBinData")){
                        if (entity.getLOTBINDATALIST().size() <= 0){
                            showToast("暂无BIN测试数据",false);
                            return;
                        }

                        List<SimpleEntity.MantissaLotBinData> list = new ArrayList<>();
                        Map<String,SimpleEntity.MantissaLotBinData> map = new HashMap<>();
                        for (int i = 0; i < entity.getLOTBINDATALIST().size(); i++) {
                            if (map.containsKey(entity.getLOTBINDATALIST().get(i).getBINNAME())){
                                SimpleEntity.MantissaLotBinData mantissaLotBinData1 = entity.getLOTBINDATALIST().get(i);
                                SimpleEntity.MantissaLotBinData mantissaLotBinData = map.get(entity.getLOTBINDATALIST().get(i).getBINNAME());
                                mantissaLotBinData.setMAINQTY(mantissaLotBinData.getMAINQTY() + mantissaLotBinData1.getMAINQTY());
                                map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),mantissaLotBinData);
                            }else {
                                map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),entity.getLOTBINDATALIST().get(i));
                            }
                        }

                        for(Map.Entry<String, SimpleEntity.MantissaLotBinData> entry : map.entrySet()){
                            list.add(entry.getValue());
                        }
                        mSampleListAdapter.setNewData(list);
                    }else {
                        Bundle bundle = new Bundle();
                        bundle.putString("LOTID",getText(etLot));
                        bundle.putString("EQPID",mEqpID);
                        bundle.putString("LOTNUM",tvLotNum.getText().toString());
                        bundle.putString("PACKAGETYPE",mPackageType);
                        FreeApi_Utils.skipWithExtraIntent("", bundle,FTTrackOutBiandaiActivity.this, entity.getGUIDE().equals("FAIL")?
                                FTTrackOutBiandaiErrorActivity.class : FTTrackOutBiandaiSuccessActivity.class);
//                        finish();
                    }

                }


            }

            @Override
            public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTFTTRACKOUT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", actionType);
        map.addProperty("EQUIPMENTID", getText(etEqpMainWork));
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
        NetUtils.requestPostNet("IF.LOTFTTRACKOUT", "LOTFTTRACKOUT", FTTrackOutBiandaiActivity.this, map, callBack);
    }

    @Override
    protected void initData() {

        initEdit(etLot, this::getLotData);

        initEdit(etEqpMainWork,s ->{

            FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                    ("正在查询LOT信息", new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(FTTrackOutBiandaiActivity.this, true, getSupportFragmentManager())) {
                        if (response.body().getResponse().getBody().getLOTLIST().size() > 0){
                            for (LotInfoEntity.LotBean s:response.body().getResponse().getBody().getLOTLIST()) {
                                lotList.add(s.getLOTID());
                            }
                            if (getText(etLot).equals("")){
                                etLot.setText(lotList.get(0));
                                tvCode.setText(lotList.get(0));
                                requestData(lotList.get(0),getText(etEqpMainWork));
                            }else {
                                tvCode.setText(getText(etLot));
                                requestData(getText(etLot),getText(etEqpMainWork));
                            }

                        }else {
                            showToast("未查询到批号信息",false);
                        }
                    }
                }
                @Override
                public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onError(response);

                }
            };

            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE", "LOTLISTRUNBYEQP");
            map.addProperty("LOTID", "");
            map.addProperty("LOTALIAS", "");
            map.addProperty("DURABLE", "");
            map.addProperty("EQUIPMENTID", s);
            map.addProperty("STEPNAME", "");
            NetUtils.requestPostNet("IF.LOTQUERY", "Common", FTTrackOutBiandaiActivity.this, map, callBack);
        });
    }

    @OnClick({R.id.tvBaseSubmit,R.id.flList})
    public void onViewClicked(View view) {
//        if (actionControl("Submit07"))return;
        switch (view.getId()){
            case R.id.tvBaseSubmit:
                if (getText(etLot).equals("")){
                    showToast("请先扫描批次号",false);
                    return;
                }
                showSubmitDialog(() -> requestBinInfo(getText(etLot),"GuideTrackout"),"是否进行下一步");
                break;
            case R.id.flList:
                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    }
                } else {
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flList.getWidth(), lotList, ivArrow, (codeS, i) -> {
                        tvCode.setText(codeS);
                        requestData(codeS,getText(etEqpMainWork));
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivArrow);
                codePop.showAsDropDown(flList, 0, 0);
                break;

        }
    }
    private void requestData(String lotID,String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    SimpleEntity entity = response.body().getResponse().getBody();
                    if (!entity.getTRACKSHOWMSG().equals("")){
                        showConfirmDialog(entity.getTRACKSHOWMSG());
                    }
                    if (entity.getLOTBINDATALIST().size() <= 0){
                        showToast("暂无BIN数据",false);
                        return;
                    }

                    mSampleListAdapter.setNewData(entity.getLOTBINDATALIST());
                }


            }

            @Override
            public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTFTTRACKOUT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "SelectClearData");
        map.addProperty("EQUIPMENTID", eqpID);
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
        NetUtils.requestPostNet("IF.LOTFTTRACKOUT", "LOTFTTRACKOUT", FTTrackOutBiandaiActivity.this, map, callBack);
    }

}
